package com.xunfang.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.xunfang.bean.Building;
import com.xunfang.bean.House;
import com.xunfang.bean.Owner;
import com.xunfang.bean.dto.OwnerQueryDTO;
import com.xunfang.bean.vo.PageVo;
import com.xunfang.common.Result;
import com.xunfang.mapper.OwnerMapper;
import com.xunfang.service.IHouseService;
import com.xunfang.service.IOwnerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.WeakHashMap;

/**
 * @author yellow Docter
 * @date 2023 -11-06
 * @desc
 */
@Service
public class OwnerServiceImpl implements IOwnerService {

    @Autowired
    private OwnerMapper ownerMapper;

    @Autowired
    private IHouseService houseService;

    @Override
    public Result addOrUpdateOwner(Owner owner) {

        //判断
        if (owner.getId() != null){
            //存在id 就是修改
            boolean flag = this.updateOwnerById(owner);
            return Result.ok(flag);

        }else{
            //没有id 添加
            boolean flag = this.addOwner(owner);
            return Result.ok(flag);
        }
    }

    @Override
    public boolean addOwner(Owner owner) {
        return ownerMapper.addOwner(owner) > 0 ;
    }

    @Override
    public boolean updateOwnerById(Owner owner) {
        return ownerMapper.updateOwnerById(owner) > 0;
    }

    @Override
    public List<Owner> findOwnersAll() {
        OwnerQueryDTO ownerQueryDTO = new OwnerQueryDTO();
        return ownerMapper.findOwners(ownerQueryDTO);
    }

    @Override
    public boolean findDeleteById(Integer id) {
        //判断  查询 house里面是否有 owner的引用
        List<House> houses = houseService.findHousesByOwner(id);
        //判断集合是否为null
        if (CollectionUtils.isEmpty(houses)){
            //可以删除 owner
           return ownerMapper.deleteOwnerById(id) > 0;
        }
        return false;
    }

    @Override
    public PageVo findOwners(Integer currentPage, Integer pageSize, OwnerQueryDTO ownerQueryDTO) {
        // 01 调用分页的方法
        Page<Owner> pageInfo =  PageHelper.startPage(currentPage,pageSize).doSelectPage( () ->{
            ownerMapper.findOwners(ownerQueryDTO);
        });

        //02 拿到 分页对象 Page
        long total = pageInfo.getTotal();
        List<Owner> list = pageInfo.getResult();
        //03 返回结果
        PageVo pageVo = new PageVo();
        pageVo.setTotal(total);
        pageVo.setData(list);
        return pageVo;
    }

    @Override
    public Owner findOwnerById(Integer id) {
        return ownerMapper.findOwnerById(id);
    }
}
